import { createStore } from 'vuex'
import { login, logout, getUserInfo } from '@/api/auth'

export default createStore({
  state: {
    // 用户信息
    user: null,
    // 访问令牌
    token: localStorage.getItem('admin_token') || '',
    // 刷新令牌
    refreshToken: localStorage.getItem('admin_refresh_token') || '',
    // 登录状态
    isLoggedIn: !!localStorage.getItem('admin_token'),
    // 侧边栏折叠状态
    sidebarCollapsed: false,
    // 面包屑导航
    breadcrumbs: []
  },

  getters: {
    // 是否已登录
    isAuthenticated: state => state.isLoggedIn && !!state.token,
    // 用户角色
    userRole: state => state.user?.roleCode || '',
    // 用户昵称
    userNickname: state => state.user?.nickname || '',
    // 用户头像
    userAvatar: state => state.user?.avatar || ''
  },

  mutations: {
    // 设置用户信息
    SET_USER(state, user) {
      state.user = user
    },

    // 设置令牌
    SET_TOKEN(state, token) {
      state.token = token
      state.isLoggedIn = !!token
      if (token) {
        localStorage.setItem('admin_token', token)
      } else {
        localStorage.removeItem('admin_token')
      }
    },

    // 设置刷新令牌
    SET_REFRESH_TOKEN(state, refreshToken) {
      state.refreshToken = refreshToken
      if (refreshToken) {
        localStorage.setItem('admin_refresh_token', refreshToken)
      } else {
        localStorage.removeItem('admin_refresh_token')
      }
    },

    // 清除认证信息
    CLEAR_AUTH(state) {
      state.user = null
      state.token = ''
      state.refreshToken = ''
      state.isLoggedIn = false
      localStorage.removeItem('admin_token')
      localStorage.removeItem('admin_refresh_token')
      localStorage.removeItem('admin_user')
    },

    // 切换侧边栏状态
    TOGGLE_SIDEBAR(state) {
      state.sidebarCollapsed = !state.sidebarCollapsed
    },

    // 设置面包屑
    SET_BREADCRUMBS(state, breadcrumbs) {
      state.breadcrumbs = breadcrumbs
    }
  },

  actions: {
    // 登录
    async login({ commit }, loginData) {
      try {
        const response = await login({
          ...loginData,
          source: 'admin'
        })

        console.log('登录响应数据:', response.data)

        // 根据实际后端返回的数据结构进行适配
        const data = response.data
        let accessToken, refreshToken, userInfo

        // 适配不同的数据结构
        if (data.accessToken) {
          // 如果直接有 accessToken
          accessToken = data.accessToken
          refreshToken = data.refreshToken
          userInfo = data.userInfo || data.user
        } else if (data.token) {
          // 如果是 token 字段
          accessToken = data.token
          refreshToken = data.refreshToken
          userInfo = data.userInfo || data.user
        } else {
          // 如果整个 data 就是用户信息，token 在其他字段
          accessToken = data.accessToken || data.token
          refreshToken = data.refreshToken
          userInfo = data
        }

        // 保存令牌
        commit('SET_TOKEN', accessToken)
        commit('SET_REFRESH_TOKEN', refreshToken)
        
        // 如果有用户信息就保存，否则后续通过 fetchUserInfo 获取
        if (userInfo) {
          commit('SET_USER', userInfo)
          localStorage.setItem('admin_user', JSON.stringify(userInfo))
        }

        return response
      } catch (error) {
        commit('CLEAR_AUTH')
        // 重新抛出错误，让调用方处理错误信息显示
        throw error
      }
    },

    // 登出
    async logout({ commit }) {
      try {
        await logout()
      } catch (error) {
        console.error('登出请求失败:', error)
      } finally {
        commit('CLEAR_AUTH')
      }
    },

    // 获取用户信息
    async fetchUserInfo({ commit, state }) {
      try {
        if (!state.token) {
          throw new Error('未找到访问令牌')
        }

        const response = await getUserInfo()
        const userInfo = response.data

        commit('SET_USER', userInfo)
        localStorage.setItem('admin_user', JSON.stringify(userInfo))

        return userInfo
      } catch (error) {
        commit('CLEAR_AUTH')
        throw error
      }
    },

    // 初始化认证状态
    initAuth({ commit }) {
      const token = localStorage.getItem('admin_token')
      const refreshToken = localStorage.getItem('admin_refresh_token')
      const userStr = localStorage.getItem('admin_user')

      if (token && userStr) {
        try {
          const user = JSON.parse(userStr)
          commit('SET_TOKEN', token)
          commit('SET_REFRESH_TOKEN', refreshToken)
          commit('SET_USER', user)
        } catch (error) {
          console.error('解析用户信息失败:', error)
          commit('CLEAR_AUTH')
        }
      }
    }
  }
})